// RiaApp.java
package pers.liaohaolong.mapzoner;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 由Deepseek生成，尚未检查，如果你要由此运行，请自行修改代码。<br>
 * 由于工作已经完成，此可视化计划将无限期推后。
 */
public class RiaApp extends Application {

    private TextField inputField;
    private TextField outputField;
    private TextField bgColorField;
    private Button selectInputBtn;
    private Button selectOutputBtn;
    private Button startBtn;
    private TextArea logArea;
    private volatile boolean isRunning = false;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("RIAZth 地图边界生成器");

        // 创建主布局
        VBox root = new VBox(10);
        root.setPadding(new Insets(10));

        // 配置区域
        GridPane configPane = createConfigPane();

        // 日志区域
        logArea = new TextArea();
        logArea.setEditable(false);
        logArea.setPrefHeight(300);
        logArea.appendText("欢迎使用地图边界生成器\n");

        // 添加到主布局
        root.getChildren().addAll(configPane, new Label("运行日志:"), logArea);

        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private GridPane createConfigPane() {
        GridPane configPane = new GridPane();
        configPane.setHgap(10);
        configPane.setVgap(10);

        // 输入文件选择
        inputField = new TextField();
        inputField.setPromptText("请选择输入图片文件");
        selectInputBtn = new Button("选择输入文件");
        selectInputBtn.setOnAction(e -> selectInputFile());

        // 输出文件选择
        outputField = new TextField();
        outputField.setPromptText("请选择输出图片位置");
        selectOutputBtn = new Button("选择输出位置");
        selectOutputBtn.setOnAction(e -> selectOutputFile());

        // 背景颜色配置
        bgColorField = new TextField();
        bgColorField.setPromptText("背景颜色RGB值，-1表示不配置");
        bgColorField.setText("-1");

        // 启动按钮
        startBtn = new Button("开始生成");
        startBtn.setOnAction(e -> startGeneration());

        // 布局配置项
        configPane.add(new Label("输入文件:"), 0, 0);
        configPane.add(inputField, 1, 0);
        configPane.add(selectInputBtn, 2, 0);

        configPane.add(new Label("输出位置:"), 0, 1);
        configPane.add(outputField, 1, 1);
        configPane.add(selectOutputBtn, 2, 1);

        configPane.add(new Label("背景颜色:"), 0, 2);
        configPane.add(bgColorField, 1, 2);

        configPane.add(startBtn, 1, 3);
        GridPane.setColumnSpan(startBtn, 2);
        GridPane.setHalignment(startBtn, javafx.geometry.HPos.RIGHT);

        return configPane;
    }

    private void selectInputFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择输入图片文件");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg"));

        File selectedFile = fileChooser.showOpenDialog(inputField.getScene().getWindow());
        if (selectedFile != null) {
            inputField.setText(selectedFile.getAbsolutePath());
        }
    }

    private void selectOutputFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择输出图片位置");
        fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("PNG文件", "*.png"));
        fileChooser.setInitialFileName("边界.png");

        File selectedFile = fileChooser.showSaveDialog(outputField.getScene().getWindow());
        if (selectedFile != null) {
            outputField.setText(selectedFile.getAbsolutePath());
        }
    }

    private void startGeneration() {
        if (isRunning) {
            showAlert(Alert.AlertType.WARNING, "警告", "生成过程已在运行中！");
            return;
        }

        String inputPath = inputField.getText();
        String outputPath = outputField.getText();

        if (inputPath.isEmpty() || outputPath.isEmpty()) {
            showAlert(Alert.AlertType.ERROR, "错误", "请填写完整的输入和输出路径！");
            return;
        }

        // 确认对话框
        Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
        confirmAlert.setTitle("确认");
        confirmAlert.setHeaderText("确认开始生成边界？");
        confirmAlert.setContentText("输入文件: " + inputPath + "\n输出文件: " + outputPath);

        confirmAlert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                startGenerationTask(inputPath, outputPath);
            }
        });
    }

    private void startGenerationTask(String inputPath, String outputPath) {
        isRunning = true;
        setControlsDisabled(true);

        Task<Void> task = new Task<>() {
            @Override
            protected Void call() throws Exception {
                updateMessage("开始处理图片...");

                try {
                    // 读取图片
                    updateMessage("读取图片...");
                    BufferedImage image = ImageIO.read(new File(inputPath));

                    // 创建MapZoner处理边界
                    MapZoner mapZoner = new MapZoner();

                    // 设置背景颜色
                    int bgColor = parseBackgroundColor();
                    if (bgColor != -1) {
                        mapZoner.setBackgroundColorRgb(bgColor);
                        updateMessage("设置背景颜色: " + bgColor);
                    }

                    // 生成边界
                    updateMessage("生成边界...");
                    mapZoner.generateBoundaries(image);

                    // 保存结果
                    updateMessage("保存结果...");
                    SaveUtils.save(image, mapZoner.getBoundaries(), java.awt.Color.BLACK.getRGB(), outputPath);

                    updateMessage("处理完成！文件已保存至: " + outputPath);
                } catch (IOException e) {
                    updateMessage("处理失败: " + e.getMessage());
                    throw e;
                }

                return null;
            }

            @Override
            protected void succeeded() {
                logArea.appendText("处理完成！\n");
                isRunning = false;
                setControlsDisabled(false);
            }

            @Override
            protected void failed() {
                logArea.appendText("处理失败: " + getException().getMessage() + "\n");
                isRunning = false;
                setControlsDisabled(false);
            }

            @Override
            protected void updateMessage(String message) {
                logArea.appendText(message + "\n");
            }
        };

        new Thread(task).start();
    }

    private int parseBackgroundColor() {
        try {
            return Integer.parseInt(bgColorField.getText());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private void setControlsDisabled(boolean disabled) {
        inputField.setDisable(disabled);
        outputField.setDisable(disabled);
        bgColorField.setDisable(disabled);
        selectInputBtn.setDisable(disabled);
        selectOutputBtn.setDisable(disabled);
        startBtn.setDisable(disabled);
    }

    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
